package com.ywu.mq.sdk.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

@Slf4j
public class HttpUtil {

    /**
     * 发送POST请求
     *
     * @param url   url
     * @param json   json
     * @param httpClient  httpClient
     * @return {@link String }
     */
    public static String doPost(String url, String json, OkHttpClient httpClient) {
        RequestBody jsonBody = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(url).post(jsonBody).build();
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("response not success: " + response);
            }
            ResponseBody body = response.body();
            if (body == null) {
                throw new IOException("response body is null");
            }
            return body.string();
        } catch (IOException e) {
            log.error("init request error : {}", e.getMessage(), e);
            throw new RuntimeException("init request error");
        }
    }
}
